package com.buaa.aiguangxi.dao;

import com.buaa.aiguangxi.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Repository
public class UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private PasswordEncoder passwordEncoder;
    public int addUser(User user){
        String sql="insert into user (username,user_password) values(?,?)";
        KeyHolder keyHolder=new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement=connection.prepareStatement(sql,PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setString(1, user.getUsername());
                preparedStatement.setString(2,passwordEncoder.encode(user.getUserPassword()));
                return preparedStatement;
            }
        },keyHolder);
        return keyHolder.getKey().intValue();
    }
    public User getUserByName(String name){
        try {
            return (User) jdbcTemplate.queryForObject("select * from user where username=?",new UserMapper(),name);
        }catch (EmptyResultDataAccessException e){
            return null;
        }
    }
    private static class UserMapper implements RowMapper{
        @Override
        public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
            User user=new User();
            user.setUserid(rs.getInt("user_id"));
            user.setUsername(rs.getString("username"));
            user.setUserPassword(rs.getString("user_password"));
            return user;
        }
    }
}
